package com.springboot2.controller;


import com.springboot2.entity.User;
import com.springboot2.service.UserService;
import com.springboot2.utils.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user/")
public class UserController {

    @Resource
    private UserService userService;

    //增
    @PostMapping("add")
    public Result save(@RequestBody User user){
        userService.add(user);
        return Result.success();
    }
    //删
    @DeleteMapping("del/{id}")
    public Result del(@PathVariable int id){
        userService.del(id);
        return Result.success();
    }
    //改
    @PutMapping("update")
    public Result update(@RequestBody User user){
        userService.update(user);
        return Result.success();
    }
    //获取对象
    @GetMapping("find/{id}")
    public Result findById(@PathVariable int id){
        return Result.success(userService.findById(id));
    }
    //分页列表
    @GetMapping("list/{pageNo}/{pageSize}")
    public Result findByPage(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String,Object> map = new HashMap<>();
        map.put("data",userService.findByPage(pageNo, pageSize));
        map.put("total",userService.count());
        return Result.success(map);
    }
    //查询条件
    @GetMapping("listParams/{pageNo}/{pageSize}/{name}")
    public Result findByPageParams(@PathVariable int pageNo,@PathVariable int pageSize,@PathVariable String name){
        Map<String,Object> map = new HashMap<>();
        map.put("data",userService.findByPageParams(pageNo, pageSize,name));
        map.put("total",userService.countParamsByName(name));
        return Result.success(map);
    }
    //批量删除
    @DeleteMapping("batch/{ids}")
    @Transactional
    public Result delAll(@PathVariable String ids){
        String[] split = ids.split(",");
        for (String id:split){
            userService.del(Integer.parseInt(id));
        }
        return  Result.success();
    }
    //登录
    @GetMapping("login/{username}/{password}")
    public Result login(@PathVariable String username, @PathVariable String password){
        return userService.login(username,password);
    }
    //登录uniapp
    @GetMapping("loginApp")
    public Result loginApp(@RequestParam String username, @RequestParam String password){
        return userService.login(username,password);
    }
}
